package com.example.bookmanager_back.controller;

import com.example.bookmanager_back.entity.Student;
import com.example.bookmanager_back.entity.vo.Result;
import com.example.bookmanager_back.entity.vo.response.BookVo;
import com.example.bookmanager_back.entity.vo.response.IndexVo;
import com.example.bookmanager_back.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class BookController {
    @Autowired
    BookService bookService;

    @GetMapping("/getIndex")
    public Result<IndexVo> getAllBorrows(){
        return Result.success(new IndexVo(bookService.getStudentCount(), bookService.getBookCount(), bookService.getBorrowList()));
    }

    @GetMapping("/getAllBooks")
    public Result<List<BookVo>> getAllBooks(){
        return Result.success(bookService.getBookVoList());
    }

    @GetMapping("/getAllStudents")
    public Result<List<Student>> getAllStudents(){
        return Result.success(bookService.getStudentList());
    }

    @PostMapping("/addBook")
    public Result<Object> addBook(String title, String desc, Double price){
        if(price == null) return Result.failure();
        try {
            bookService.addBook(title, desc, price);
            return Result.success("success added");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    @PostMapping("/deleteBook")
    public Result<Object> deleteBook(Integer id){
        if(id == null) return Result.failure();
        try {
            bookService.deleteBook(id);
            return Result.success("success deleted");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    @PostMapping("/addBorrow")
    public Result<Object> addBorrow(Integer sid, Integer bid){
        if(sid == null || bid == null) return Result.failure();
        try {
            bookService.addBorrow(sid, bid);
            return Result.success("success added");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    @PostMapping("/returnBook")
    public Result<Object> returnBook(Integer id){
        if(id == null) return Result.failure();
        try {
            bookService.returnBook(id);
            return Result.success("success deleted");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }
}
